package cn.xuanxuanyuhua.crm.service.impl;


import cn.xuanxuanyuhua.crm.domain.Employee;
import cn.xuanxuanyuhua.crm.mapper.EmployeeMapper;
import cn.xuanxuanyuhua.crm.mapper.PermissionMapper;
import cn.xuanxuanyuhua.crm.mapper.RoleMapper;
import cn.xuanxuanyuhua.crm.query.QueryObject;
import cn.xuanxuanyuhua.crm.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Employee> list = employeeMapper.queryForList(qo);
        return new PageInfo(list);
    }

    @Override
    public void delete(Long id) {
        employeeMapper.deleteRelationByEmployeeId(id);
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> list() {
        return employeeMapper.selectAll();
    }

    /**
     * 保存员工与其所拥有的权限
     * @param entity
     * @param ids
     */
    @Override
    public void saveOrUpdate(Employee entity, Long[] ids){
        if (entity.getId() != null) {
            employeeMapper.deleteRelationByEmployeeId(entity.getId());
            employeeMapper.updateByPrimaryKey(entity);
        }else{
            Md5Hash hash = new Md5Hash(entity.getPassword(),entity.getName());
            entity.setPassword(hash.toString());
            employeeMapper.insert(entity);
        }
        if (ids != null) {
            for (Long id : ids) {
                employeeMapper.insertEmployeeAndRoleRelation(entity.getId(),id);
            }
        }
    }

    @Override
    public Boolean checkUsernamae(String name) {
        return employeeMapper.selectUsername(name) == null;
    }

    @Override
    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
    }

    @Override
    public List<String> getRolesByEmployeeId(Long id) {

        return roleMapper.selectRolesByEmployeeId(id);
    }


    @Override
    public List<Employee> selectEmpsById(Long id) {
        return employeeMapper.selectEmpsById(id);
    }

    @Override
    public List<String> getPermissionByEmployee(Long id) {
        return permissionMapper.selectExpressionByEmployeeId(id);
    }




    @Override
    public Employee getInfoByUsername(String username) {
        return employeeMapper.selectInfoByUsername(username);
    }




}
